package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.startegy.SaveOrderStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SaveOrderStrategyContext implements ApplicationContextAware {

    //定义一个map类型的成员变量,存储策略实现的对象
    private static final Map<String, SaveOrderStrategy> STRATEGY_MAP = new HashMap<>();

    // 定义从Map中获取具体策略对象的方法
    public static final SaveOrderStrategy getSaveOrderStrategy(String payWay) {
        return STRATEGY_MAP.get(payWay);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(SaveOrderStrategy.class).values().forEach(saveOrderStrategy -> {
            STRATEGY_MAP.put(saveOrderStrategy.getPayWay(), saveOrderStrategy);
        });
    }
}
